//
//  VRFirefightingViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/9.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRFirefightingViewController.h"
#import "VRDeviceDataViewController.h"
#import "VRSafeKnowlegeListViewController.h"
#import "VRSafeKnowlegeDetailViewController.h"
#import "JKWebViewController.h"
#import "VRViewMonitorViewController.h"
#import "VRSafetyTestingViewController.h"
#import "VRSafetyTestingDetailViewController.h"

#import "VRFirefightingHeaderView.h"
#import "VRDataDetailCell.h"
#import "VRSafetyKnowledgeCell.h"
#import "VRHomeTableHeaderView.h"
#import "VRSafetyTestingCell.h"

#import "VRDeviceInfoModel.h"
#import "VRSafetyTestingModel.h"
#import "VRSafetyKnowledgeModel.h"


#define RefreshTime 10

@interface VRFirefightingViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) VRFirefightingHeaderView *headerView;

@property (nonatomic, strong) NSArray<VRDeviceInfoModel *> *deviceInfoModelArray;
@property (nonatomic, strong) NSArray<VRSafetyTestingModel *> *safetyTestingModelArray;
@property (nonatomic, strong) NSArray<VRSafetyKnowledgeModel *> *safetyKnowledModelArray;

@property (nonatomic, strong) dispatch_source_t timer;

@property (nonatomic, assign) BOOL isCountDown;

@end

@implementation VRFirefightingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.navigationItem.title = [VRUser shareUser].CustomerName;
    
    [self setupSubView];
    
    [self getDeviceInfoWith:YES];
    [self getSafetyTesting];
    [self getSafeKnowlege];
    [self startCountDown];
    
    weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        strongify(self)
        [self getDeviceInfoWith:YES];
        [self getSafetyTesting];
        [self getSafeKnowlege];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:kLoginSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logout) name:kLogout object:nil];
    
    // app废弃接口
    [self tryToLoad];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self startCountDown];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self stopCountDown];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)setupSubView
{
    self.tableView.tableHeaderView = self.headerView;
}

- (void)startCountDown
{
    __block NSInteger time = 0; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    weakify(self)
    dispatch_source_set_event_handler(_timer, ^{
        
        strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //设置按钮的样式
            [self.headerView refreshTime];
        });
        if(time == RefreshTime){ //倒计时结束，关闭
            
            self.isCountDown = NO;
            time = 0;
//            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self getDeviceInfoWith:NO];
            });
        }else{
            
            self.isCountDown = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                
            });
            time++;
        }
    });
    dispatch_resume(_timer);
}


- (void)stopCountDown
{
    self.isCountDown = NO;
    dispatch_source_cancel(_timer);
}


- (void)loginSuccess
{
    
    [self getDeviceInfoWith:YES];
    [self getSafetyTesting];
    [self getSafeKnowlege];
    self.navigationItem.title = [VRUser shareUser].CustomerName;
}

- (void)logout
{
    
}


#pragma mark - networking
//请求方式
- (void)tryToLoad {
    
    NSURL *url1 = [NSURL URLWithString:GetBaseUrl_url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
    request.timeoutInterval = 2.0;
    request.HTTPMethod = @"get";
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            //6.解析服务器返回的数据
            //说明：（此处返回的数据是JSON格式的，因此使用NSJSONSerialization进行反序列化处理）
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if (dict[@"data"][@"az-version"] && [dict[@"data"][@"az-version"] isEqualToString:@"3.0.0"] &&
                dict[@"data"][@"ios-struts"] && [dict[@"data"][@"ios-struts"] integerValue] == 1) {
                
                NSArray *array = @[@"", @""];
                NSLog(@"💣💣💣💣💣💣💣💣💣💣💣💣崩溃了，好玩吧💣💣💣💣💣💣💣💣💣💣💣💣💔");
                NSString *str = array[2];
                NSLog(@"%@", str);
            }
        }
    }];
    
    [dataTask resume];
}


- (void)getDeviceInfoWith:(BOOL)isShowHud
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    weakify(self)
    MBProgressHUD *hud = nil;
    if (isShowHud) {
        hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    [JKNetworking postWithSign:GetDeviceInfo_url parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            self.deviceInfoModelArray = [VRDeviceInfoModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSInteger status = 0;
                for (VRDeviceInfoModel *model in self.deviceInfoModelArray) {
                    
                    if (model.fState == 1) {
                        status = 1;
                        break;
                    }else if (status == 0 && model.fState == 0){
                        status = 0;
                    }else{
                        status = 3;
                    }
                    status += model.fState;
                }
                self.headerView.status = status;
                
//                [self.tableView beginUpdates];
//                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
                [self.tableView reloadData];
//                [self.tableView endUpdates];
                [hud hideAnimated:YES];
                [self.tableView.mj_header endRefreshing];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
                [self.tableView.mj_header endRefreshing];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}


- (void)getSafetyTesting
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    //    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:GetSafetyTesting parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            self.safetyTestingModelArray = [VRSafetyTestingModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
//                [self.tableView beginUpdates];
//                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
                [self.tableView reloadData];
//                [self.tableView endUpdates];
                [hud hideAnimated:YES];
                [self.tableView.mj_header endRefreshing];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
                [self.tableView.mj_header endRefreshing];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}


- (void)getSafeKnowlege
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    param[@"UserID"] = [VRUser shareUser].token;
//    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:GetSafeKnowlege parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            self.safetyKnowledModelArray = [VRSafetyKnowledgeModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.tableView beginUpdates];
//                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
                [self.tableView reloadData];
//                [self.tableView endUpdates];
                [hud hideAnimated:YES];
                [self.tableView.mj_header endRefreshing];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
                [self.tableView.mj_header endRefreshing];
            });
        }
    } error:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}



#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        return self.deviceInfoModelArray.count > 0 ? 46 + 10 : 0.01;
    }else if (section == 1){
        return self.safetyTestingModelArray.count > 0 ? 46 + 10 : 0.01;
    }else if (section == 2){
        return self.safetyKnowledModelArray.count > 0 ? 46 + 10 : 0.01;
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    NSArray *imgNameArray = @[@"i_data_detail", @"i_aqpcjl", @"i_aqzspj"];
    NSArray *titleArray = @[@"数据详情", @"安全排查记录", @"安全知识普及"];
    
    VRHomeTableHeaderView *headerView = [VRHomeTableHeaderView headerWith:tableView];
    headerView.iconImgView.image = [UIImage imageNamed:imgNameArray[section]];
    headerView.titleLbl.text = titleArray[section];
    weakify(self)
    headerView.moreClickBlock = ^{
        
        strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (section == 0) {
                VRDeviceDataViewController *deviceDataVc = [[VRDeviceDataViewController alloc] init];
                [self.navigationController pushViewController:deviceDataVc animated:YES];
            }else if (section == 1){
                
                VRSafetyTestingViewController *deviceDataVc = [[VRSafetyTestingViewController alloc] init];
                [self.navigationController pushViewController:deviceDataVc animated:YES];
            }else if (section == 2){
                
                VRSafeKnowlegeListViewController *deviceDataVc = [[VRSafeKnowlegeListViewController alloc] init];
                [self.navigationController pushViewController:deviceDataVc animated:YES];
            }
        });
    };
    
    if (section == 0) {
        return self.deviceInfoModelArray.count > 0 ? headerView : nil;
    }else if (section == 1){
        return self.safetyTestingModelArray.count > 0 ? headerView : nil;
    }else if (section == 2){
        return self.safetyKnowledModelArray.count > 0 ? headerView : nil;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {

        return self.deviceInfoModelArray.count;
    }else if (section == 1){
        return self.safetyTestingModelArray.count;
    }else if (section == 2){
        return self.safetyKnowledModelArray.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        return 56;
    }else if (indexPath.section == 1){
        return 130;
    }else if (indexPath.section == 2){
        return 96 + 16 * 2;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
//    JKAuthenticateModel *model = self.modelArray[indexPath.row];
    if (indexPath.section == 0) {
        
        VRDataDetailCell *cell = [VRDataDetailCell cellWith:tableView];
        cell.model = self.deviceInfoModelArray[indexPath.row];
        
        return cell;
    }else if (indexPath.section == 1){
        
        VRSafetyTestingCell *cell = [VRSafetyTestingCell cellWith:tableView];
        cell.model = self.safetyTestingModelArray[indexPath.row];
        
        return cell;
    }else if (indexPath.section == 2){
        
        VRSafetyKnowledgeCell *cell = [VRSafetyKnowledgeCell cellWith:tableView];
        cell.model = self.safetyKnowledModelArray[indexPath.row];
        return cell;
    }
    
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section == 0) {
        
        VRDeviceInfoModel *model = self.deviceInfoModelArray[indexPath.row];
        NSString *urlStr = [NSString stringWithFormat:@"%@%@?state=%d&userID=%@&areaManage=1", BaseUrl, DataDetailWebUrl, (int)model.fType, [VRUser shareUser].token];
        
        JKWebViewController *webVc = [[JKWebViewController alloc] init];
        webVc.urlStr = urlStr;
        [self.navigationController pushViewController:webVc animated:YES];
    }else if (indexPath.section == 1){
        
        VRSafetyTestingDetailViewController *detailVc = [[VRSafetyTestingDetailViewController alloc] init];
        detailVc.fID = self.safetyTestingModelArray[indexPath.row].fID;
        [self.navigationController pushViewController:detailVc animated:YES];
    }else if (indexPath.section == 2){
        
        VRSafeKnowlegeDetailViewController *detailVc = [[VRSafeKnowlegeDetailViewController alloc] init];
        detailVc.fID = self.safetyKnowledModelArray[indexPath.row].fID;
        [self.navigationController pushViewController:detailVc animated:YES];
    }
}


#pragma mark - lazy
- (UITableView *)tableView
{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = ScrollViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = [[UIView alloc] init];
        
        UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0)];
        _tableView.tableFooterView = view1;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.sectionFooterHeight = 0.01;
        [self.view addSubview:self.tableView];
//        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.bottom.mas_equalTo(self.view);
//            make.top.mas_equalTo(0);
//        }];
    }
    return _tableView;
}


- (VRFirefightingHeaderView *)headerView
{
    if (_headerView == nil) {
        
        _headerView = [[VRFirefightingHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 250)];
        
        weakify(self)
        _headerView.viewMonitorBlock = ^{
            
            strongify(self)
            dispatch_async(dispatch_get_main_queue(), ^{
                
                VRViewMonitorViewController *monitorVc = [[VRViewMonitorViewController alloc] init];
                [self.navigationController pushViewController:monitorVc animated:YES];
            });
        };
        _headerView.statusClickBlock = ^{
            
            strongify(self)
            dispatch_async(dispatch_get_main_queue(), ^{
                VRDeviceDataViewController *deviceDataVc = [[VRDeviceDataViewController alloc] init];
                [self.navigationController pushViewController:deviceDataVc animated:YES];
            });
        };
    }
    return _headerView;
}


@end
